package com.sky.Protocol;

import com.sky.Sdk.ClientBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.concurrent.TimeUnit;

/**
 * Created by sun on 2017-06-16.
 */
public class MessageClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private ClientBootstrap clientBootstrap;

    public MessageClientHandler(ClientBootstrap clientBootstrap) {
        this.clientBootstrap = clientBootstrap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) {
        System.out.println(messageProtocol.getHeader().getMsgType());
        System.out.println(messageProtocol.getBody());
    }

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        MessageProtocol msg = null;

        if(IdleStateEvent.class.isAssignableFrom(evt.getClass()))
        {
            IdleStateEvent event = (IdleStateEvent)evt;
            if(event.state() == IdleState.READER_IDLE)
            {
                System.out.println("read idle---");
                msg = new MessageProtocol("ping");
                ctx.writeAndFlush(msg);

                System.out.println("send ping---");
            }
            else if(event.state() == IdleState.WRITER_IDLE){
                msg = new MessageProtocol("----------ping--------");
                ctx.writeAndFlush(msg);

                System.out.println("--------send ping---");
            }else if(event.state() == IdleState.ALL_IDLE) {
                System.out.println("all idle---");
            }
        }else {
            //远程主机强制关闭连接
            System.out.println("remote close connection---");
            ctx.channel().close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    clientBootstrap.connect();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },1, TimeUnit.SECONDS);

        super.channelInactive(ctx);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println(cause);
        ctx.close();
    }
}
